package com.idp.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.idp.app.dto.AppFeedbackDto;
import com.idp.app.dto.AppFeedbackSearchDto;
import com.idp.app.entity.AppFeedbackEntity;
import com.idp.app.mapper.AppFeedbackMapper;
import com.idp.app.service.AppFeedbackService;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.common.utils.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 意见与反馈Service实现类
 * @author King
 */
@Service("appFeedbackService")
public class AppFeedbackServiceImpl implements AppFeedbackService {

	@Autowired
	private AppFeedbackMapper appFeedbackMapper;

	/**
	 * 状态：1待处理
 	 */
	private static final String FEEDBACK_STATUS_TODO = "1";

	@Override
	public PageModel<AppFeedbackDto> findByPage(AppFeedbackSearchDto appFeedbackSearchDto) {

		PageModel<AppFeedbackDto> page = new PageModel<AppFeedbackDto>();

		page.setList(appFeedbackMapper.getList(appFeedbackSearchDto));

		return page;
	}

	@Override
	public AppFeedbackDto getById(String id) {

		if(ObjectUtil.isEmpty(id)) {

			throw new SystemException(MessageEnum.PARAM_ERROR);
		}

		AppFeedbackDto appFeedbackDto = appFeedbackMapper.getById(id);

		if(appFeedbackDto == null) {

			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		return appFeedbackDto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(AppFeedbackDto appFeedbackDto) {

		AppFeedbackEntity appFeedbackEntity = new AppFeedbackEntity();
		BeanUtil.copyProperties(appFeedbackDto, appFeedbackEntity);

		appFeedbackEntity.setStatus(FEEDBACK_STATUS_TODO);
		appFeedbackEntity.setCreateUser(ContextUtil.getLoginUserId());
		appFeedbackEntity.setCreateTime(new Date());

		appFeedbackMapper.insert(appFeedbackEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(AppFeedbackDto appFeedbackDto) {

		AppFeedbackEntity appFeedback = appFeedbackMapper.selectById(appFeedbackDto.getId());
		if(appFeedback == null) {
			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		BeanUtil.copyProperties(appFeedbackDto, appFeedback);

		appFeedback.setHandleUser(ContextUtil.getLoginUserId());
		appFeedback.setHandleTime(new Date());

		appFeedbackMapper.updateById(appFeedback);
	}

}
